from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin as DefaultUserAdmin

from utils.decorators import log_oper_decorator
from users.models import UserOperationLog

# Register your models here.

User = get_user_model()

# 定义全局的页面配置
admin.AdminSite.site_title = "Python定时任务后台"
admin.AdminSite.site_header = "Python定时任务后台"
admin.AdminSite.empty_value_display = 'unknown'


# @log_oper_decorator
class UserAdmin(DefaultUserAdmin):
    list_display = ['id', 'username', 'nickname', 'email', 'get_age', 'gender', 'mobile']
    list_display_links = ['id', 'username', 'nickname']
    list_filter = ('gender', 'is_active', 'is_staff', 'is_superuser')
    filter_horizontal = ('groups',)
    search_fields = ('id', 'username', 'nickname', 'email', 'mobile')
    fieldsets = (
        ('基本信息', {
            'fields': ('id', 'username', 'nickname', 'avatar', 'gender',
                       'birthday', 'email', 'mobile', 'is_active', 'last_login'),
        }),
        ('职员信息', {
            'fields': ('is_staff', 'is_superuser', 'groups', 'date_joined'),
        }),
        ('其他信息', {
            'fields': ('first_name', 'last_name', 'password'),
        })
    )
    readonly_fields = ('id', 'date_joined', 'last_login')
    list_per_page = 50


@log_oper_decorator
class UserOperationLogAdmin(admin.ModelAdmin):
    list_display = ['id', 'user', 'operation', 'resource', 'c_time', 'm_time']
    search_fields = ['user', 'operation', 'resource', 'content']
    list_filter = ['user__username', 'operation', 'c_time']
    fieldsets = (
        ('信号基本信息', {
            'fields': ('id', 'user', 'operation', 'resource', 'content')
        }),
        ('其他信息', {
            'fields': ('c_time', 'm_time')
        })
    )
    list_per_page = 50

    def has_change_permission(self, request, obj=None):
        """
        所有人不允许修改记录的内容
        """
        return False

    def has_delete_permission(self, request, obj=None):
        """
        所有人不允许删除记录的内容
        """
        return False

    def delete_queryset(self, request, queryset):
        queryset.delete()


admin.site.register(User, UserAdmin)
admin.site.register(UserOperationLog, UserOperationLogAdmin)
